<?php
class Generator extends Item{

    public $codeContent;
    public $fileName;
    public $filePath;
    public $template;
    public $name;
    public $type;

    public function __construct($fileName,$type){
//        global $config;
        $this->config = Basic::app()->getConfigs();
        $this->setDefaultTemplate('system.class.generator.template.t'.$type);
        $fileName = $type.'.'.$fileName;
        $filePath = $this->config['base']['root'].$this->getFilePath($fileName);
        $pathinfo = pathinfo($filePath);
        $this->name = ucwords($pathinfo['filename']);
        $this->type = $type;
        $content = $this->getContent($filePath);
        echo PHP_EOL.$content.PHP_EOL;
        $this->buildFileTree($filePath);
        return $this->createFile($content, $filePath);
    }

    public static function create($fileName,$type='controller'){
        new self($fileName,$type);
    }

    public function mkdirs($dir, $mode = 0777,$recursive=true){
        if (is_dir($dir) || @mkdir($dir, $mode, $recursive)) return TRUE;
        return false;
    }

    public function getFilePath($fileName){
        return nameToPath($fileName);
    }

    public function setDefaultTemplate($defualtTemplate){
        $this->template = $defualtTemplate;
    }

    public function getTemplateFile(){
        return nameToPath($this->template);
    }

    public function setTemplateFile($fileName){
        $this->template = $fileName;
    }


    public function buildFileTree($filePath){
        $pathInfo = pathinfo($filePath);
        if($this->mkdirs($pathInfo['dirname'])){
            return true;
        }
        return false;
    }

    public function createFile($content, $filePath){
        if(!file_exists($filePath)){
            $fp = fopen($filePath,'ab');
            if(fwrite($fp, $content)){
                fclose($fp);
                echo PHP_EOL.'create File ['.$this->type.'] '.$this->name.' successfully!!'.PHP_EOL;
                return $this->name;
            }
            return false;
        }
        return false;
    }



    public function getContent(){
        $config = $this->config;
        $_templatePath = $this->config['base']['root'].nameToPath($this->template);
        ob_start();
        ob_implicit_flush(false);
        require($_templatePath);
        return ob_get_clean();
    }
}